package com.cdream.basic.algorithm.leetcode.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author cdream
 * @date 6/10/21
 */
public class Question56 {
    public static void main(String[] args) {
        new Question56().merge(new int[][]{{1, 3}, {2, 6}, {8, 10}});
    }

    public int[][] merge(int[][] intervals) {
        if (intervals.length == 0) {
            return new int[0][2];
        }
        Arrays.sort(intervals, Comparator.comparingInt(interval -> interval[0]));

        List<int[]> merged = new ArrayList<>();

        for (int i = 0; i < intervals.length; i++) {
            int[] val = intervals[i];
            if (merged.size() == 0) {
                merged.add(val);
            } else {
                int[] lastArray = merged.get(merged.size() - 1);
                if (lastArray[1] < val[0]) {
                    merged.add(val);
                } else {
                    lastArray[1] = Math.max(lastArray[1], val[1]);
                }
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }
}
